package com.skit.common.manager

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.skit.common.bean.StatusResult
import com.skit.common.bean.User
import com.skit.common.config.RetrofitClient
import com.skit.common.event.EventMessage
import com.skit.common.http.HttpUtils
import com.skit.common.retrofit.UserProtocol
import com.skit.common.utils.ToastUtils
import org.greenrobot.eventbus.EventBus

object UserManager {
    private var sAppContext: Context? = null
    private lateinit var sharedPreferences: SharedPreferences
    private const val name = "name"
    private const val USER_DATA = "userData"
    private const val email = "email"
    private const val token = "token"
    private const val icon = "icon"
    private const val id = "id"
    private const val createTime = "createTime"

    @JvmStatic
    fun init(context: Context) {
        sAppContext = context
        sharedPreferences =
            context.getSharedPreferences("user", Context.MODE_PRIVATE)
    }

    @JvmStatic
    val user: User?
        get() {
            val string = sharedPreferences.getString(USER_DATA, null) ?: return null
            return Gson().fromJson(string, User::class.java)
        }

    /**
     * 用户信息存储
     *
     * @param user 传入用户模型User
     * @return 返回存储是否成功
     */
    @JvmStatic
    fun saveUser(user: User): Boolean {
        val edit =
            sharedPreferences.edit()
        edit.putString(USER_DATA, Gson().toJson(user))
        return edit.commit()
    }

    /**
     * 退出登录
     */
    fun logout() {
        sharedPreferences.edit().clear().apply()//清空edit
    }


    fun checkLogin() {
        val user = this.user ?: return
        val userProtocol = RetrofitClient.getService(UserProtocol::class.java)
        val userInfo =
            userProtocol.getUserInfo(user.id, user.token)
        HttpUtils.doRequest<User>(userInfo,
            object : HttpUtils.RequestFinishCallback<User> {
                override fun getRequest(result: StatusResult<User>?) {
                    if (result == null || !result.isSuccess) {
                        if (result != null) {
                            if (result.status == 401) {
                                logout()
                                EventBus.getDefault()
                                    .post(EventMessage(EventMessage.MessageCode.LOGOUT))
                            }
                            ToastUtils.showToast(result.msg)
                        }
                        return
                    }
                    val data = result.data
                    if (data != null) {

                    }
                }
            }
        )
    }
}